package com.jz.digital.view;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.AttrRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jz.digital.R;
import com.jz.digital.base.EditInputCallback;
import com.jz.digital.listener.OnTextChangedListener;
import com.jz.digital.utils.PassWordInputFilter;

/**
 * Copyright (c) 2019 深圳市爱都科技有限公司. All rights reserved.
 *
 * @Author: xyb
 * @CreateDate: 2019-12-26 12:21
 * @description
 */
public class ViewMePassword extends FrameLayout {
    private ImageView mMeSeepassIv;
    private NoMenuEditText mEtPassword;
    private ImageButton mIbDelete;
    private boolean mIsPassShow = false;
    private Drawable mBackground;
    private ColorStateList mTextColor;
    private ColorStateList mTextColorHint;
    private String mTextHint;
    private int mTextSizeHint;
    private OnTextChangedListener mOnTextChangedListener;
    private TextWatcher mTextWatcher;
    private boolean isShowPwdStyle;
    private LinearLayout container;

    public ViewMePassword(@NonNull Context context) {
        this(context, null);
    }

    public ViewMePassword(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ViewMePassword(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewMe);
        mBackground = a.getDrawable(R.styleable.ViewMe_meBackground);
        mTextColor = a.getColorStateList(R.styleable.ViewMe_meTextColor);
        mTextColorHint = a.getColorStateList(R.styleable.ViewMe_meTextColorHint);
        mTextHint = a.getString(R.styleable.ViewMe_meTextHint);
        mTextSizeHint = a.getInteger(R.styleable.ViewMe_meTextSizeHint, 13);
        isShowPwdStyle = a.getBoolean(R.styleable.ViewMe_meShowPwdStyle, true);
        a.recycle();
        initView();
        initListener();
    }

    /**
     * 文字变化后的监听
     *
     * @param listener
     */
    public void setOnTextChangedListener(OnTextChangedListener listener) {
        mOnTextChangedListener = listener;
    }

    /**
     * 设置编辑框的内容
     *
     * @param text
     */
    public void setPassword(CharSequence text) {
        mEtPassword.setText(text);
    }

    public void addFilter(InputFilter... filters) {
        if (filters == null || filters.length == 0) return;
        for (InputFilter filter : filters) {
            if (filter instanceof PassWordInputFilter) {
                ((PassWordInputFilter) filter).setEditInputCallback(new EditInputCallback() {
                    @Override
                    public void errorTip() {
//                        NormalToast.showToast(IdoApp.getAppContext().getString(R.string.key_2919));
                    }
                });
            }
        }
        mEtPassword.setFilters(filters);
    }

    public void clearFilter() {
        mEtPassword.setFilters(new InputFilter[0]);
    }

    /**
     * 获取密码编辑框的内容
     *
     * @return
     */
    public String getPassword() {
        return mEtPassword.getText().toString();
    }

    private void initView() {
        View view = LayoutInflater.from(getContext())
                .inflate(R.layout.widget_me_password, this, true);
        container = view.findViewById(R.id.container);
        mEtPassword = view.findViewById(R.id.me_password_et);
        mMeSeepassIv = view.findViewById(R.id.me_seepassword_iv);
        mIbDelete = view.findViewById(R.id.me_ib_delete_pass);

        if (mBackground != null)
//            container.setBackground(mBackground);
        if (mTextColor != null)
            mEtPassword.setTextColor(mTextColor);
        if (mBackground == null) {
//            ColorUtil.shapeSolid(container, 10, textFieldBackgroundColor());
        }
        if (mTextColorHint == null) {
//            mTextColorHint = ColorStateList.valueOf(textFieldPlaceholderColor());
        }
        mEtPassword.setHintTextColor(mTextColorHint);
        if (TextUtils.isEmpty(mTextHint) && mEtPassword.getHint() != null) {
            mTextHint = mEtPassword.getHint().toString();
        }
        if (TextUtils.isEmpty(mTextHint)) return;
        if (mTextSizeHint > 0) {
            // 新建一个可以添加属性的文本对象
            SpannableString ss = new SpannableString(mTextHint);
            // 新建一个属性对象,设置文字的大小
            AbsoluteSizeSpan ass = new AbsoluteSizeSpan(mTextSizeHint, true);
            // 附加属性到文本
            ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            // 设置hint
            mEtPassword.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
        } else {
            mEtPassword.setHint(mTextHint);
        }
    }

    private void initListener() {
        if (isShowPwdStyle) {
            mMeSeepassIv.setVisibility(VISIBLE);
            showOrHindePass(mIsPassShow, mEtPassword, mMeSeepassIv);
            mMeSeepassIv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mIsPassShow = !mIsPassShow;
                    showOrHindePass(mIsPassShow, mEtPassword, mMeSeepassIv);
                }
            });
        }
        mIbDelete.setOnClickListener(v -> mEtPassword.setText(""));
        //给editText增加获得焦点的响应
        mEtPassword.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
//                if (hasFocus) {
//                    ColorUtil.shapeSolidStroke(container, 10, 1, textFieldBorderLineColor());
//                    //      container.setBackgroundResource(R.drawable.shape_rectangle_line_black_bg_white_10_corner);
//                } else {
//                    ColorUtil.shapeSolid(container, 10, textFieldBackgroundColor());
//                }
            }
        });
    }

    private void showOrHindePass(boolean isPassShow, EditText mEtPassword, ImageView mIvLock) {
        if (isPassShow) {
            mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            mEtPassword.setTypeface(Typeface.DEFAULT);
            mIvLock.setImageResource(R.mipmap.ic_login_see_selected);
        } else {
            mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT
                    | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            mEtPassword.setTypeface(Typeface.DEFAULT);
            mIvLock.setImageResource(R.mipmap.ic_login_see_normal);
        }
        mEtPassword.postInvalidate();
        //切换后将EditText光标置于末尾
        CharSequence charSequence = mEtPassword.getText();
        if (charSequence != null) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mTextWatcher == null) {
            mTextWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (mOnTextChangedListener != null) {
                        mOnTextChangedListener.changed(s.toString());
                    }
                    // 控制删除按钮的可见
                    //mIbDelete.setVisibility(TextUtils.isEmpty(s.toString()) ? GONE : VISIBLE);
                    mIbDelete.setVisibility(View.GONE);
//                    if(s.length()==0){
//                        mEtPassword.getPaint().setFakeBoldText(false);
//                    }else{
//                        mEtPassword.getPaint().setFakeBoldText(true);
//                    }
                }
            };
        }
        mEtPassword.addTextChangedListener(mTextWatcher);
    }


    @Override
    protected void onDetachedFromWindow() {
        mEtPassword.removeTextChangedListener(mTextWatcher);
        super.onDetachedFromWindow();
    }

    /**
     * 设置名字编辑框内容
     *
     * @param text
     */
    public void setNameHint(CharSequence text) {
        mTextHint = text.toString();
        if (mTextSizeHint > 0) {
            // 新建一个可以添加属性的文本对象
            SpannableString ss = new SpannableString(mTextHint);
            // 新建一个属性对象,设置文字的大小
            AbsoluteSizeSpan ass = new AbsoluteSizeSpan(mTextSizeHint, true);
            // 附加属性到文本
            ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            // 设置hint
            mEtPassword.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
        } else {
            mEtPassword.setHint(mTextHint);
        }
    }

}
